/*
 * jgpush.js
 * @author zhangwei  2017-06-12
 * 极光推送的相关代码的封装
 */

(function(window){
	'use strict';
	var jpush = function(){
		this._init();
	};
	jpush.prototype = {
		_init:function(){
			if(typeof(api) == 'undefined'){
				console.log('该插件只能在apicloud下运行');
			}else{
				this.ajpush = api.require('ajpush');
				this.systemType = api.systemType;
				if(this.systemType == 'ios'){ 			// ios下自动初始化ajpush模块，不用再加载
					this.listenNoticeClick();
				}else{
					this.loadAjpush(this.ajpush);
				};

				this.isPushStopped(this.ajpush); 		// 检测推送服务状态
				//this.stopPush(this.ajpush); 			//监听停止推送服务
				this.setMsgListener(this.ajpush); 		//设置app在前台的情况下的消息监听
				this.bindUserAliasAndTags(this.ajpush); //绑定别名 和标签
				this.onResume(this.ajpush); 			//通知极光当前应用恢复到前台
				this.onPause(this.ajpush);				//通知极光当前应用进入到后台
				// this.setIosBadge(0);
			}
		},

		//安卓下需要初始化极光
		loadAjpush:function(ajpush){
			var self = this;
			ajpush.init(function(ret,err){
				// console.log('初始化情况' + JSON.stringify(ret));
				if(ret && ret.status){
					self.listenNoticeClick(); 		 //apicloud调用通知栏用此方法（此app主要针对聊天调用的通知栏)
					self.listenAndroidNoticeClick(); //被第三方调起的通知栏用此方法
				}else{
					console.log('err' + JSON.stringify(err));
				}
			});
		},

		//监听被第三方调起的通知栏消息点击(此处仅安卓用);
		listenAndroidNoticeClick:function(){
			var self =  this;
			api.addEventListener({
			    name: 'appintent'
			}, function(ret, err) {
				//alert('android-click' +JSON.stringify(ret));
			    if (ret && ret.appParam.ajpush) {
			        self.pushMsgHandle(ret.appParam.ajpush,'click');
			    }
			})
		},

		//监听通知栏消息点击
		listenNoticeClick:function(){
			var self =  this;
			api.addEventListener({
			    name: 'noticeclicked'
			}, function(ret, err) {
				//alert('ios-click' +JSON.stringify(ret));
			    if (ret && ret.value) {
			        self.pushMsgHandle(ret.value,'click');
			    }
			})
		},

		// 设置消息监听
		setMsgListener:function(ajpush){
			var self = this;
			ajpush.setListener(function(ret){
				if(ret){
					// console.log('设置消息监听' + JSON.stringify(ret));
					self.pushMsgHandle(ret);
					//针对苹果 app 在前台的情况下不发送通知的问题
					if(self.systemType == 'ios' && $api.getStorage('isOpened') == 1){
						self.sendNotification(ret);
					};
				}
			});
		},

		//绑定用户别名和标签
		bindUserAliasAndTags:function(ajpush){
			var self = this;
			var uid = $api.getStorage('user').id;
			var param = {alias:uid,tags:['tag1' +uid ,'tag2' +uid]};
			ajpush.bindAliasAndTags(param,function(ret) {
			    var statusCode = ret.statusCode;
			    // console.log('绑定代码'+ statusCode);
			});
		},
		//设置角标(ios有效)
		setIosBadge:function(num){
			var ajpush = this.ajpush;
			ajpush.setBadge({
			    badge:num
			});
		},

		//查看推送服务是否停止
		isPushStopped:function(ajpush){
			var self =  this;
			ajpush.isPushStopped(function(ret) {
				// console.log('推送服务状态' + JSON.stringify(ret));
			    if(ret && ret.isStopped){
			    	self.resumePush(ajpush);
			    }
			});
		},
		//开启当前推送服务
		resumePush:function(ajpush){
			ajpush.resumePush(function(ret) {
			    if(ret && ret.status){
			    	console.log('开启推送成功');
			    }
			});
		},
		//用户退出停止推送
		stopPush:function(ajpush){
			api.addEventListener({
			    name: 'stopPush'
			}, function(ret, err){
			    if( ret ){
			    	ajpush.stopPush(function(ret) {
					    if(ret && ret.status){
					    	console.log('停止推送成功');
					    }
					});
			    }
			});
		},
		//通知极光推送SDK当前应用恢复到前台。
		onResume:function(ajpush){
			api.addEventListener({
			    name: 'resume'
			}, function(ret, err){
				//console.log( '到前台了');
				ajpush.onResume();
				$api.setStorage('isOpened','1');
				//alert('判断前后台' + $api.getStorage('isOpened'));
			});
		},

		//通知极光推送SDK当前应用退入到后台。
		onPause:function(ajpush){
			api.addEventListener({
			    name: 'pause'
			}, function(ret, err){
				//console.log('到后台了');
				ajpush.onPause();
				$api.setStorage('isOpened','0');
				// alert('判断前后台' + $api.getStorage('isOpened'));
			});
		},

		//手动调起通知栏(针对ios系统-app在前台的时候不能调起通知栏的问题)
		sendNotification:function(ret){
			var data 	   = ret.data;
			api.notification({
			    notify: {
			    	title:ret.title,
			        content: ret.content,
			        extra:ret.extra,
			    },
			    'vibrate':[500,500],
			    'sound':'default',
			    'light':false,
			}, function(ret, err){

			});
		},
		//统一推送消息的处理
		pushMsgHandle:function(ret,click){
			// alert('推送消息内容' + JSON.stringify(ret));

			if(typeof(ret) == 'string'){
				ret = JSON.parse(ret);
			}

			if(click){
				if(this.systemType == 'ios'){
					this.setIosBadge(0);  // 设置角标为 0
				};

				if(ret.type && ret.type == 'im'){
					//聊天消息的通知栏点击
					api.openWin({
					    name: 'chat_win',
					    url: './chat/chat_win.html',
					    pageParam: {
					        targetId: ret.targetId,
							targetNickname: ret.nickname,
							conversationType: ret.event
					    }
					});
				}else{
					// 系统推送的通知栏点击
					api.openWin({
					    name: 'message_list_win',
					    url: './message/message_list_win.html'
					});
				}
			}else{
				//推送服务器相关字段
				if(typeof(ret.extra) == 'string'){
					var extra = JSON.parse(ret.extra);
				}else{
					var extra = ret.extra;
				};

				//发送到各自定义的监听处理,
				api.sendEvent({
				    name: 'push_notice',
				    extra: {
				    	data:ret
				    }
				});
			}

		},
	};
	window.jpush = jpush;

})(window);